import string
import urllib.request
from urllib.parse import quote
from bs4 import BeautifulSoup
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 定义一个去除空格和换行符的函数
def nospace(text):
    return text.strip().replace(" ", "").replace("\n", "") if text else ""

# 城市编码字典
city_code = {
    '北京': '530',
    '上海': '538',
    '广州': '763',
    '深圳': '765',
    '天津': '531',
    '武汉': '736',
    '西安': '854',
    '成都': '801',
    '沈阳': '599',
    '南京': '635',
    '杭州': '653',
    '苏州': '639',
    '重庆': '551',
    '长沙': '749',
    '厦门': '682',
    '南昌': '691'
}

def get_job_info(url):
    try:
        # 发送HTTP请求并获取页面内容
        resp = urllib.request.urlopen(url)
        content = resp.read().decode("utf-8")
        logging.info(f"Successfully fetched page content from {url}")
    except Exception as e:
        logging.error(f"Failed to fetch page content from {url}: {e}")
        return []

    # 使用BeautifulSoup解析页面
    soup = BeautifulSoup(content, features="lxml")

    # 提取招聘信息列表
    job_list = []
    job_items = soup.select(".joblist-box__item")  # 根据实际页面结构调整选择器

    for job in job_items:
        job_dic = {}

        # 岗位名称
        job_name_elem = job.select_one(".jobinfo__name")
        job_name = job_name_elem.get_text(strip=True) if job_name_elem else "N/A"

        # 工资处理
        salary_elem = job.select_one(".jobinfo__salary")
        salary = salary_elem.get_text(strip=True) if salary_elem else "N/A"
        salary = nospace(salary)

        job_sal = 5000  # 默认值
        if '天' in salary:
            job_sal = int(salary.split("-")[0]) * 30
        elif '千' in salary:
            job_sal = int(salary.split("千")[0]) * 1000
        elif '万' in salary:
            job_sal = float(salary.split("万")[0]) * 10000

        # 公司名称
        company_name_elem = job.select_one(".companyinfo__name")
        company_name = company_name_elem.get_text(strip=True) if company_name_elem else "N/A"
        company_name = nospace(company_name)

        # 工作地点、工作经验、学历要求
        job_msg = job.select(".jobinfo_other-info-item")
        if len(job_msg) >= 3:
            job_place = nospace(job_msg[0].get_text())
            job_exp = nospace(job_msg[1].get_text())
            job_education = nospace(job_msg[2].get_text())
        else:
            job_place, job_exp, job_education = "N/A", "N/A", "N/A"

        # 将数据存入字典
        job_dic['job_name'] = job_name
        job_dic['job_salary'] = job_sal
        job_dic['company_name'] = company_name
        job_dic['job_place'] = job_place[:2]  # 取前两个字符作为工作地点
        job_dic['job_experience'] = job_exp
        job_dic['job_education'] = job_education

        job_list.append(job_dic)

    return job_list

def main():
    # 用户输入城市和岗位名称
    city = input("请输入城市:")
    city_code_val = city_code.get(city, "")
    if not city_code_val:
        logging.error("Invalid city input")
        return

    jobName = input("请输入相关岗位:")

    # 构造URL并转义中文字符
    url = f"https://sou.zhaopin.com/?jl={city_code_val}&kw={jobName}&p=1"
    url = quote(url, safe=string.printable)

    # 获取并打印招聘信息
    job_list = get_job_info(url)
    for job in job_list:
        print(job)

if __name__ == "__main__":
    main()
